package com.mfcxy.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mfcxy.entity.Role;
import com.mfcxy.entity.RolePermission;
import com.mfcxy.entity.UserRole;
import com.mfcxy.mapper.IRoleMapper;
import com.mfcxy.mapper.IUserRoleMapper;
import com.mfcxy.service.IUserRoleService;

/**
 * 
 * @author mfcxy
 *
 */
@Service
public class UserRoleService extends BaseService implements IUserRoleService {

	@Autowired
	private IUserRoleMapper userRoleMapper;

	@Autowired
	private IRoleMapper roleMapper;

	/**
	 * 查询用户角色
	 */
	@Override
	public List<Role> selectURList(int uid) {
		// TODO Auto-generated method stub
		List<Role> rlist = roleMapper.selectList();
		List<UserRole> urlist = userRoleMapper.selectURList(uid);
		for (Role role : rlist) {
			for (UserRole userRole : urlist) {
				if (userRole.getRoleid() == role.getRid()) {
					role.setChecked(true);
				}
			}
		}
		return rlist;
	}

	/**
	 * 修改用户角色
	 */
	@Override
	public void insertUR(String rids, int uid) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		// 清空原有权限
		userRoleMapper.delUR(uid);
		// 如果有提交任何新权限数据
		if (!rids.equals("")) {
			// 字符串转数组
			String[] sArray = rids.split(",");
			ArrayList<UserRole> urs = new ArrayList<>();
			// 创建RolePermission 对象
			for (String string : sArray) {
				UserRole rp = new UserRole();
				rp.setId(getTools().getUUID32());
				rp.setRoleid(Integer.parseInt(string));
				rp.setUserid(uid);
				urs.add(rp);
			}
			userRoleMapper.insertUR(urs);
		}
	}

}
